package editor;

import org.yaml.snakeyaml.Yaml;

import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Map;


public class texteditor<RSyntaxTextArea> extends JFrame {
    private JFrame jf;
    private JMenuBar menuBar;
    private Font font;
    private JMenu menu_File, menu_Search, menu_View, menu_Manage, menu_Help;
    private JMenuItem menuItem_search;
    private JMenuItem menuItem_new, menuItem_open, menuItem_save, menuItem_Exit, menuItem_Print, menuItem_PDF;
    private JMenuItem menuItem_copy, menuItem_Paste, menuItem_cut;
    private JMenuItem menuItem_date;
    private JMenuItem menuItem_about;
    private JMenuItem menuItem1,menuItem2,menuItem3;
    private JPopupMenu menu;
    public String filepathname = null;
    public String filename = "New File";
    public JTextArea edit_text_Area;
    private JScrollPane sp;


    public void mainfjame(String title) {
        initMenuBar();
        initEditArea();
        try {
            initYAML();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        jf = new JFrame(title); //creat main window
        jf.setVisible(true);
        jf.setSize(700,600);
        jf.setLocation(600,200);
        sp = new JScrollPane(edit_text_Area);
        sp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        edit_text_Area.setComponentPopupMenu(menu);
        jf.add(sp);
        jf.setJMenuBar(menuBar);

        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jf.dispose();
        jf.setVisible(true);
    }

    public void creatJFrame(String title){
        initMenuBar();
        initEditArea();
        JFrame jFrame = new JFrame(title);
        jf = jFrame;
        jFrame.setVisible(true);
        jFrame.setSize(700,600);
        jFrame.setLocation(600,200);
        sp = new JScrollPane(edit_text_Area);
        sp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jFrame.add(sp);
        jFrame.setJMenuBar(menuBar);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    public void initYAML() throws FileNotFoundException {
        Map map;
        File file = new File("src/main/resources/application.yml");
        Yaml yaml = new Yaml();
        map = (Map) yaml.load(new FileInputStream(file));
        font = new Font(map.get("font-style").toString(),Font.PLAIN,(int)map.get("font-size"));
        System.out.println(font.getFontName());
    }   //initialize YAML configuration


    public void initMenuBar() {
        menuBar = new JMenuBar();
        menuBar.setPreferredSize(new Dimension(700,35));
      // initialize menubar
        menu_File = new JMenu("File");
        menu_File.setSize(100,300);
        menu_File.setMnemonic('f');
        menu_Search = new JMenu("Search");
        menu_Search.setMnemonic('s');
        menu_View = new JMenu("View");
        menu_View.setMnemonic('v');
        menu_Manage = new JMenu("Manage");
        menu_Manage.setMnemonic('m');
        menu_Help = new JMenu("Help");
        menu_Help.setMnemonic('h');

        menu = new JPopupMenu();
        menuItem1 = new JMenuItem("Copy");
        menuItem2 = new JMenuItem("Paste"); // Initialize the right-click menu
        menuItem3 = new JMenuItem("Cut");
        menu.add(menuItem1);
        menu.add(menuItem2);
        menu.add(menuItem3);

        menu_File.setPreferredSize(new Dimension(50,35));
        menu_Search.setPreferredSize(new Dimension(70,35));
        menu_View.setPreferredSize(new Dimension(60,35));
        menu_Manage.setPreferredSize(new Dimension(70,35));
        menu_Help.setPreferredSize(new Dimension(60,35));


        menuItem_new = new JMenuItem("New");
        menuItem_new.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jf.dispose();
                texteditor texteditor = new texteditor();
                texteditor.creatJFrame("No Title");
          // New window
            }
        });
        menuItem_open = new JMenuItem("Open");  // Open new file
        menuItem_open.addActionListener(new ActionListener() {
            final JFileChooser fileChooser;
            {
                fileChooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "记事本文件(.txt)","txt");
                FileNameExtensionFilter filter1 = new FileNameExtensionFilter(
                        "源代码(.java/.py/.cpp/.similar)","java", "py", "cpp","similar");
                fileChooser.setFileFilter(filter);
                fileChooser.setFileFilter(filter1);
            }  //Select the file to be opened, and divide the file into categories
            @Override
            public void actionPerformed(ActionEvent e) {
                int i = fileChooser.showOpenDialog(getContentPane());
                if (i == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    filename = selectedFile.getName();
                    filepathname = selectedFile.getAbsolutePath();
                    String text = new Open().openitem(filepathname, filename);
                    edit_text_Area.setText(text);
                    jf.setTitle(selectedFile.getName());
                    if (text == null) {
                        jf.remove(sp);
                        sp = new JScrollPane(new Open().opencoloritem(filepathname, filename));
                        jf.add(sp);
                    }
                    jf.dispose();
                    jf.setVisible(true);
                }
            }
        });

        menuItem_save = new JMenuItem("Save");
        menuItem_save.addActionListener(new ActionListener() {
       //save document
            @Override
            public void actionPerformed(ActionEvent e) {
                if (filepathname == null){
                    JFileChooser fileChooser = new JFileChooser();
                    int i = fileChooser.showSaveDialog(getContentPane());
                    if(i == JFileChooser.APPROVE_OPTION){
                        File selectedFile = fileChooser.getSelectedFile();
                        Save save = new Save();
                        filepathname = selectedFile.getAbsolutePath();
                        filename = selectedFile.getName();
                        save.SaveItem(selectedFile.getAbsolutePath()+".txt",edit_text_Area.getText());
                        setTitle(selectedFile.getName());
                    }
                }
                else {
                    Save save = new Save();
                    save.SaveItem(filepathname,edit_text_Area.getText());
                }
            }
        });


        menuItem_Exit = new JMenuItem("Exit");
        menuItem_Exit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        menuItem_PDF = new JMenuItem("To PDF");
        //Export to PDF format file. The premise is that the current file has been saved
        menuItem_PDF.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (filepathname == null){
                    JFileChooser fileChooser = new JFileChooser();
                    int i = fileChooser.showSaveDialog(getContentPane());
                    if(i == JFileChooser.APPROVE_OPTION){
                        File selectedFile = fileChooser.getSelectedFile();
                        Save save = new Save();
                        filepathname = selectedFile.getAbsolutePath();
                        filename = selectedFile.getName();
                        save.SaveItem(selectedFile.getAbsolutePath(),edit_text_Area.getText());
                        setTitle(selectedFile.getName());
                    }
                }
                File file = new File(filepathname);
                TurnintoPDF turnintoPDF = new TurnintoPDF();
                try {
                    turnintoPDF.PDFItem(filepathname,filename,file);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }



            }
        });
        menuItem_Print = new JMenuItem("Print");
        // Print function
        menuItem_Print.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (filepathname != null){
                    printfile(filepathname);
                }else {
                    JFileChooser fileChooser = new JFileChooser();
                    int i = fileChooser.showSaveDialog(getContentPane());
                    if(i == JFileChooser.APPROVE_OPTION){
                        File selectedFile = fileChooser.getSelectedFile();
                        Save save = new Save();
                        filepathname = selectedFile.getAbsolutePath();
                        filename = selectedFile.getName();
                        save.SaveItem(selectedFile.getAbsolutePath(),edit_text_Area.getText());
                        setTitle(selectedFile.getName());
                        printfile(filepathname);
                    }
                }
            }
        });

        menu_File.add(menuItem_new);
        menu_File.add(menuItem_open);
        menu_File.add(menuItem_save);
        menu_File.add(menuItem_Print);
        menu_File.add(menuItem_PDF);
        menu_File.add(menuItem_Exit);

        menuItem_search = new JMenuItem("search");
        menu_Search.add(menuItem_search);
        // Search function, enter the word you are looking for in the pop-up text area
        // and click the button
        menuItem_search.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new MyJDialog(texteditor.this).setVisible(true);
            }
        });

        menuItem_copy = new JMenuItem("Copy");
        menuItem_copy.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String copystring = edit_text_Area.getSelectedText();
                StringSelection ss = new StringSelection(copystring);
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
            }
        });

        menuItem_Paste = new JMenuItem("Paste");
        menuItem_Paste.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
                try {
                    String sel = (String) t.getTransferData(DataFlavor.stringFlavor);
                    edit_text_Area.replaceSelection(sel);
                } catch (Exception exc) {
                    System.out.println("not string flavour");
                }
            }
        });
        menuItem_cut = new JMenuItem("Cut");
        menu_Manage.add(menuItem_copy);
        menu_Manage.add(menuItem_cut);
        menu_Manage.add(menuItem_Paste);

        menuItem_date = new JMenuItem("Date and time");
        // Display the time at the top of the text area
        menu_View.add(menuItem_date);
        menuItem_date.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String s = edit_text_Area.getText();
                edit_text_Area.setText(DateFormat.getDateInstance().format(new Date()).toString() + "\n" + s);
            }
        });


        menuItem_about = new JMenuItem("About");
        menu_Help.add(menuItem_about);
        menuItem_about.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "WenNian 20008020" + "\n" + "Xingruxiao 20007883" + "\n" +"159251 assignmen1","About",JOptionPane.PLAIN_MESSAGE);
            }
        });

        menuBar.add(menu_File);
        menuBar.add(menu_Search);
        menuBar.add(menu_View);
        menuBar.add(menu_Manage);
        menuBar.add(menu_Help);

        menuItem_copy.addActionListener(new ItemListener());
        menuItem_cut.addActionListener(new ItemListener());
        menuItem_Paste.addActionListener(new ItemListener());
        //menuItem_search.addActionListener(new ItemListener());
        menuItem1.addActionListener(new ItemListener());
        menuItem2.addActionListener(new ItemListener());
        menuItem3.addActionListener(new ItemListener());



    }

    public void initEditArea() {
        //Initialize the text area
        edit_text_Area = new JTextArea();
        Font font = new Font("宋体",Font.PLAIN,26);
        edit_text_Area.setFont(font);
        JScrollPane scrollPane = new JScrollPane(edit_text_Area);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

    }

    public void printfile(String name){
        File file = new File(name);
        PrintRequestAttributeSet pri = new HashPrintRequestAttributeSet();
        DocFlavor docFlavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        PrintService[] printService = PrintServiceLookup.lookupPrintServices(docFlavor,pri);
        PrintService printService1 = ServiceUI.printDialog(null,200,200, printService,null,docFlavor,pri);
        if (printService1 != null){
            DocPrintJob job = printService1.createPrintJob();
            FileInputStream fis;
            try {
                fis = new FileInputStream(file);
                DocAttributeSet das = new HashDocAttributeSet();
                Doc doc = new SimpleDoc(fis, docFlavor, das);
                job.print(doc, pri);
            } catch (FileNotFoundException | PrintException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public Dimension getPreferredSize() {
        Dimension d = super.getPreferredSize();
        d.width = Math.max(d.width, 400); // set minimums
        d.height = Math.max(d.height, 300);
        return d;
    }

    class MyJDialog extends JDialog{
        public MyJDialog(texteditor frame){
            super(frame,"search",true);
            Container container = getContentPane();
            setBounds(200,200,300,250);
            TextField textField = new TextField();
            JButton jButton = new JButton("Next");
            jButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Search search = new Search();
                    search.searchtxt(edit_text_Area,textField.getText());
                    textField.requestFocus();
                }
            });
            container.setLayout(new BorderLayout());
            container.add(BorderLayout.SOUTH,jButton);
            container.add(BorderLayout.CENTER,textField);
        }
    }

    public class ItemListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            JMenuItem menuItem = (JMenuItem) e.getSource();
            System.out.println(menuItem.getText());
            //Used to monitor the right-click menu
            switch (menuItem.getText()) {
                case "Copy": {
                    String copystring = edit_text_Area.getSelectedText();
                    StringSelection ss = new StringSelection(copystring);
                    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
                    break;
                }
                case "Cut": {
                    String copystring = edit_text_Area.getSelectedText();
                    StringSelection ss = new StringSelection(copystring);
                    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
                    edit_text_Area.replaceSelection("");

                    break;
                }
                case "Paste":
                    Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
                    try {
                        String sel = (String) t.getTransferData(DataFlavor.stringFlavor);
                        edit_text_Area.replaceSelection(sel);
                    } catch (Exception exc) {
                        System.out.println("not string flavour");
                    }
                    break;
            }
        }
    }
    public static void main(String[] args) {
        texteditor texteditor = new texteditor();
        texteditor.mainfjame("Texteditor");
    }

}
